package com.yswl.yeeduo.ui.fragment;

import java.util.Map;
import java.util.TreeMap;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.yswl.yeeduo.App;
import com.yswl.yeeduo.R;
import com.yswl.yeeduo.http.KAsyncTask.TaskDelegate;
import com.yswl.yeeduo.ui.activity.AboutAppActivity;
import com.yswl.yeeduo.ui.activity.DetailMoneyActivity;
import com.yswl.yeeduo.ui.activity.LoginActivity;
import com.yswl.yeeduo.ui.activity.RankingListActivity;
import com.yswl.yeeduo.ui.activity.SettingActivity;
import com.yswl.yeeduo.ui.bean.UserMoneyBean;
import com.yswl.yeeduo.ui.db.WxUserInfoDao;
import com.yswl.yeeduo.ui.task.DrawMoneyTask;
import com.yswl.yeeduo.ui.task.UserMoneyTask;
import com.yswl.yeeduo.ui.task.WXAuthByUm;
import com.yswl.yeeduo.ui.tool.ServiceAuthManager;
import com.yswl.yeeduo.ui.tool.ToastUtil;
import com.yswl.yeeduo.ui.tool.UserManger;
import com.yswl.yeeduo.view.RoundImageView;
import com.yswl.yeeduo.view.dialog.ComfireAlertDialog;
import com.yswl.yeeduo.view.dialog.ComfireAlertDialog.ComfireAlertDialogListner;

/**
 * 我的收益
 * 
 * @author Administrator
 *
 */

public class MyMoneyFragment extends Fragment implements OnClickListener, TaskDelegate, ComfireAlertDialogListner {
	public static final String TAG = "MyMoneyFragment";

	private RoundImageView mUserHead;
	private TextView mUserName;
	private TextView mUserTotalMoney;
	private TextView mUserBalance;
	private Button wxLoginBtn;
	protected ImageLoader imageLoader;
	// private DisplayImageOptions mOptions;

	public final static int BUTTON_LGOIN_FLAG = 100101;// 作为按钮登录
	public final static int BUTTON_WITHDRAW_CASH_FLAG = 100102;// 作为提现

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View ui = inflater.inflate(R.layout.fragment_mymoney, null);
		imageLoader = ImageLoader.getInstance();
		// mOptions = ImageUtil.getDefaultOptions() ;
		mUserHead = (RoundImageView) ui.findViewById(R.id.user_head_img);
		mUserName = (TextView) ui.findViewById(R.id.user_name_tv);
		mUserTotalMoney = (TextView) ui.findViewById(R.id.user_total_money_tv);
		mUserBalance = (TextView) ui.findViewById(R.id.user_balance_tv);
		wxLoginBtn = (Button) ui.findViewById(R.id.wx_login_btn);
		wxLoginBtn.setOnClickListener(this);
		wxLoginBtn.setTag(BUTTON_LGOIN_FLAG);

		// 下
		ui.findViewById(R.id.user_ranking_list_btn).setOnClickListener(this);
		ui.findViewById(R.id.user_deital_money_btn).setOnClickListener(this);
		ui.findViewById(R.id.sys_setting_btn).setOnClickListener(this);
		ui.findViewById(R.id.about_app_btn).setOnClickListener(this);

		registerMessageReceiver();
		return ui;
	}

	private void initLoginState() {// 头像
		if (App.getInstance().isLogin) {
			wxLoginBtn.setText("微信提现");
			wxLoginBtn.setTag(BUTTON_WITHDRAW_CASH_FLAG);
			mUserName.setText(UserManger.getInstance().getUserName(getActivity()));
			initHead();
		} else {
			wxLoginBtn.setText("登录");
			wxLoginBtn.setTag(BUTTON_LGOIN_FLAG);
			mUserName.setText("请登录");
			mUserTotalMoney.setText("￥--");
			mUserBalance.setText("￥--");
			String imageUri = "drawable://" + R.drawable.header_default;
			imageLoader.displayImage(imageUri, mUserHead);
		}

	}

	private void initHead() {
		if (UserManger.getInstance().isAuthed(getActivity())) {
			String userHeadUri = WxUserInfoDao.getInstance().queryAllUser().get(0).headimgurl;
			imageLoader.displayImage(userHeadUri, mUserHead);
		} else {
			String imageUri = "drawable://" + R.drawable.header_default;
			imageLoader.displayImage(imageUri, mUserHead);
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (hidden) {
			// onPause();
		} else {
			initLoginState();
			sendUserMoneyRequest();
		}
	}

	/**
	 * Um统计
	 */
	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageEnd(this.getClass().getSimpleName());
		initLoginState();
		sendUserMoneyRequest();
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageStart(this.getClass().getSimpleName());
	}

	@Override
	public void onClick(View v) {

		int id = v.getId();
		Intent intent;
		switch (id) {
		case R.id.wx_login_btn:// 登录
			int flag = (Integer) v.getTag();
			if (flag == BUTTON_LGOIN_FLAG) {
				jumpLoginActivity();
			} else if (flag == BUTTON_WITHDRAW_CASH_FLAG) {
				if (UserManger.getInstance().isAuthed(getActivity())) { // 绑定多微信就可以提现没有的话
					drawMoneyRequest();
				} else {
					ComfireAlertDialog.getComfireAlertDialog(getActivity(), this, -9999, null, "未绑定微信，绑定微信才能提现！", "取消", "绑定").show();
				}
			}
			break;
		case R.id.user_ranking_list_btn:// 排行榜
			if (App.getInstance().isLogin) {
				intent = new Intent(getActivity(), RankingListActivity.class);
				startActivity(intent);
			} else {
				jumpLoginActivity();
			}

			break;
		case R.id.user_deital_money_btn:// 收益明细
			if (App.getInstance().isLogin) {
				intent = new Intent(getActivity(), DetailMoneyActivity.class);
				startActivity(intent);
			} else {
				jumpLoginActivity();
			}
			break;
		case R.id.sys_setting_btn:// 系统设置
			intent = new Intent(getActivity(), SettingActivity.class);
			startActivity(intent);
			break;
		case R.id.about_app_btn:// 关于一点
			// intent = BaseWebViewActivity.createIntent(getActivity(),
			// "http://www.baidu.com", "关于我们", false, false,
			// WebViewActivity2.class);
			intent = new Intent(getActivity(), AboutAppActivity.class);
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	private void jumpLoginActivity() {
		startActivity(new Intent(getActivity(), LoginActivity.class));
	}

	@Override
	public void faild_TaskDelegate(int taskId, Object object) {
		switch (taskId) {
		case USERMONEY_REQUEST_ID:

			break;
		case DRAWMONEY_REQUEST_ID:
			// 提现返回失败
			ToastUtil.showShortMsg(object.toString());
			break;

		default:
			break;
		}
		ToastUtil.showShortMsg(object.toString());
	}

	@Override
	public void success_TaskDelegate(int taskId, Object object) {
		switch (taskId) {
		case USERMONEY_REQUEST_ID:
			UserMoneyBean userMoney = (UserMoneyBean) object;
			if (userMoney != null) {
				mUserTotalMoney.setText("￥" + userMoney.totalMoney);
				mUserBalance.setText("￥" + userMoney.money);
			}
			break;
		case DRAWMONEY_REQUEST_ID:
			// 提现返回成功 重新请求金额
			sendUserMoneyRequest();
			ToastUtil.showShortMsg(object.toString());
			ComfireAlertDialog.getComfireAlertDialog(getActivity(), this, -8888, object.toString(), object.toString(), "忽略", "查看");
			break;
		default:
			break;
		}

	}

	private final static int USERMONEY_REQUEST_ID = 11001;
	private final static int DRAWMONEY_REQUEST_ID = 11002;

	// 获取用户金额请求
	public void sendUserMoneyRequest() {
		if (!App.getInstance().isLogin) {
			return;
		}
		Map<String, String> params = new TreeMap<String, String>();
		String userId = ServiceAuthManager.getUserId(getActivity());
		params.put("userId", userId);
		params.put("api_key", ServiceAuthManager.getToken(getActivity()));
		new UserMoneyTask(getActivity(), USERMONEY_REQUEST_ID, this).execute(params);
	}

	// 提现请求
	private void drawMoneyRequest() {
		MobclickAgent.onEvent(getActivity(), "user_wxdrawing_onclick");
		Map<String, String> params = new TreeMap<String, String>();
		String userId = ServiceAuthManager.getUserId(getActivity());
		params.put("userId", userId);
		params.put("source", "2");
		params.put("api_key", ServiceAuthManager.getToken(getActivity()));
		new DrawMoneyTask(getActivity(), DRAWMONEY_REQUEST_ID, this).execute(params);
	}

	@Override
	public void ComfireAlertDialogSure(int targetId, AlertDialog dialog, Object param) {
		dialog.cancel();
		if (targetId == -9999) {
			MobclickAgent.onEvent(getActivity(), "user_bindwx");
			WXAuthByUm auth = new WXAuthByUm(getActivity());
			auth.WxAuthByUM();
		} else if (targetId == -8888) {
			try {
				Intent intent = new Intent();
				ComponentName cmp = new ComponentName(" com.tencent.mm ", "com.tencent.mm.ui.LauncherUI");
				intent.setAction(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setComponent(cmp);
			} catch (Exception e) {
				ToastUtil.showShortMsg("亲，没有安装微信哦！");
			}
		}

	}

	@Override
	public void ComfireAlertDialogCancel(int targetId, AlertDialog dialog) {
		dialog.cancel();
	}

	private Handler handle = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 0) {
				initHead();
			}
		};
	};

	/**
	 * 
	 * @param con
	 * @param toFragment
	 *            刷新用户头像
	 */
	public static void sendBroadcast(Context con) {
		Intent intent = new Intent();
		intent.setAction(MESSAGE_RECEIVED_ACTION);
		LocalBroadcastManager.getInstance(con).sendBroadcast(intent);
	}

	/**
	 * 广播接收者 用来通知数据刷新
	 */
	public static final String MESSAGE_RECEIVED_ACTION = "notification_refresh_head";

	private BroadcastReceiver mReceiver;

	public void registerMessageReceiver() {
		LocalBroadcastManager mBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
		IntentFilter filter = new IntentFilter();
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
					handle.sendEmptyMessage(0);
				}
			}
		};
		mBroadcastManager.registerReceiver(mReceiver, filter);
	}

	// 解除注册广播
	@Override
	public void onDestroy() {
		LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
		super.onDestroy();
	}

}
